import React, {Component} from 'react';
import {
    Text,
    View,
    StyleSheet,
    ScrollView,
    Image,
    TextInput,
    Dimensions,
    InteractionManager,
    TouchableOpacity,
    KeyboardAvoidingView,
    NativeModules,
    BackHandler,
    Alert,
    Platform
} from 'react-native';
let {width, height} = Dimensions.get('window');
import px2dp from '../../utils/px2dp'
import NetUtil from '../../common/NetUtil';
import config from '../../config/config';
import themeconfig from '../../config/theme';
import commonStyles from '../../styles/commonstyles';

import {getProductList} from './actions';

import ProductListItem from './productListItem';

import {connect} from 'react-redux';

import CLNavigatorHeader from '../../component/CLNavigatorHeader'
import LmmKeyboardAvoidingView from '../../component/LmmKeyboardAvoidingView'
import CLImagesView from '../../component/CLImagesView'
import CLEditView from '../../component/CLEditView'
import CLTagView from '../../component/CLTagView'
import CLListItem from '../../component/CLListItem'
import ActionSheet from 'react-native-actionsheet'
import {ArrayUtil} from '../../utils/common'
import {getQiniuToken} from '../../utils/commonHttp'
import {addProduct, getProductDetail, updateProduct, getProductCategoryDetail, chooseBrand, chooseCategory} from './actions';
import {chooseImage, editRichContent, toast} from '../../utils/NativeUtil';
import StepInfo from './stepInfo';

import styles from './styles';

const CANCEL_INDEX = 0;
const DESTRUCTIVE_INDEX = 4;
const options = ['取消', '拍照上传', '选择图片'];
import {naviPush, naviBack} from '../../navigatorApp/actions'

const TAG_DESTRUCTIVE_INDEX = 6;
const tag_options = [
    '取消',
    '新品',
    '特价',
    '折扣',
    '促销',
    '处理'
];
const backoptions = [
    '已保存,直接退出',
    '取消'
];

class AttView extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        let values = this.props.values;
        let tagViewContainer;

        let valueArray = [];

        if (values != undefined && values != "") {
            valueArray = values.split(";");
        }

        if (valueArray.length > 0) {
            const tagViews = valueArray.map((item, i) => {
                return <TouchableOpacity key={i} onPress={() => {
                    this.props.delAtt(item)
                }}>
                    <CLTagView
                        customStyle={{
                            margin: 5,
                            borderColor: themeconfig.maincolor
                        }}
                        title={item}
                        textStyle={{
                            fontSize: 14,
                            color: themeconfig.maincolor
                        }}/>
                </TouchableOpacity>
            })
            tagViewContainer = <View style={styles.tagcontainer}>
                {tagViews}
            </View>
        }

        return <View style={{
            backgroundColor: "#eee"
        }}>
            <View style={styles.attcontainer}>
                <Text style={styles.atttextStyle}>
                    {this.props.title}
                </Text>
            </View>
            {tagViewContainer}
            <View style={styles.attbottom}>
                <TextInput
                    value={this.props.inputValue}
                    placeholder={this.props.placeholder}
                    editable={true}
                    underlineColorAndroid={'transparent'}
                    style={{
                        marginLeft: 10,
                        padding: 0,
                        flex: 1,
                        borderWidth: 0
                    }}
                    onChangeText={(text) => this.props.onChangeText(text)}/>
                <TouchableOpacity onPress={() => {
                    this.props.confirm()
                }}>
                    <CLTagView
                        customStyle={{
                            margin: 5,
                            borderColor: themeconfig.maincolor
                        }}
                        title="确定"
                        textStyle={{
                            fontSize: 14,
                            color: themeconfig.maincolor
                        }}/>
                </TouchableOpacity>
            </View>
        </View>
    }
}

class ProductAdd extends Component {

    static navigationOptions = ({navigation, screenProps}) => {
        const {params = {}} = navigation.state;
        let catId = navigation.state.params.catId;
        let title = '其他编辑';
        if (catId == 56) {
            title = '宠物编辑';
        } else if (catId == 6) {
            title = '商品编辑';
        } else if (catId == 100) {
            title = '服务编辑';
        }
        let header = <CLNavigatorHeader navigation={navigation} title={title} leftAction={params.backAction}/>;
        return {header};
    };

    _backAction = () => {
        // this.BackActionSheet.show();
        const self = this;
        Alert.alert('确认保存',
        "未保存的商品信息在退出后将无法被获取",
        [
            {text: '取消', onPress: () => {}},
            {text: '继续退出', onPress: () => { self.props.naviBack();}},
        ]);
    };

    constructor(props) {
        super(props);
        this.imgType = 0;
        this.isEdit = false;

        this.catId = props.navigation.state.params.catId;

        this.state = {
            colorsAtts: [],
            sizesAtts: [],
            inputSize: "",
            inputColor: "",
            name: "",
            catCode: "",
            // marketPrice: "",
            shopPrice: "",//零售价
            tradePrice: "",//批发价格
            soldOut: "0",
            img: "",
            colors: "",
            sizes: "",
            remark: "",
            slides: [],
            tag: "",
            detail: ""
        }
    }

    componentDidMount() {
        this.props.navigation.setParams({backAction: this._backAction});
        let {state} = this.props.navigation;
        this.goodsId = undefined;
        if (state.params != undefined) {
            this.goodsId = state.params.goodsId;
            if (this.goodsId != undefined) {
                this.isEdit = true;
                let params = {
                    token: this.props.token,
                    id: this.goodsId
                };
                const self = this;

                getProductDetail(params, (detail) => {

                    if (detail.catCode != undefined) {
                        self.props.getProductCategoryDetail(detail.catCode);
                    }

                    self.setState({
                        name: detail.goodsName,
                        // marketPrice: (detail.marketPrice / 100).toFixed(2),
                        shopPrice: (detail.shopPrice / 100).toFixed(2),
                        tradePrice: (detail.tradePrice / 100).toFixed(2),
                        img: detail.goodsThumb == undefined
                            ? ""
                            : detail.goodsThumb,
                        remark: detail.goodsBrief,
                        slides: detail
                            .goodsSlider
                            .split(";"),
                        catCode: detail.catCode,
                    })
                })
            } else {
                this.props.chooseBrand('');
                this.props.chooseCategory({});
            }
        }
    }

    delColors = (item) => {
        let attrs = this.state.colorsAtts;
        ArrayUtil.delete(attrs, item);
        this.setState({colorsAtts: attrs});
    }

    delSizes = (item) => {
        let attrs = this.state.sizesAtts;
        ArrayUtil.delete(attrs, item);
        this.setState({sizesAtts: attrs});
    }

    confirmColor = () => {
        let attrs = this.state.colorsAtts;
        attrs.push(this.state.inputColor);
        this.setState({atts: attrs});
    }

    confirmSize = () => {
        let attrs = this.state.sizesAtts;
        attrs.push(this.state.inputSize);
        this.setState({atts: attrs});
    }

    checkValue = () => {
        if (this.props.token == undefined || this.props.token == "") {
            toast("用户不存在，请重新登录");
            return false;
        }

        if (this.state.name == undefined || this.state.name == "") {
            toast("请输入商品名称");
            return false;
        }

        if (this.state.img == undefined || this.state.img == "") {
            toast("请设置商品主图");
            return false;
        }

        // if (this.state.marketPrice == undefined || this.state.marketPrice == "") {
        //     toast("请输入市场价");
        //     return false;
        // }

        if (this.state.shopPrice == undefined || this.state.shopPrice == "") {
            toast("请输入零售价");
            return false;
        }

        // if (this.state.tradePrice == undefined || this.state.tradePrice == "") {
        //     toast("请输入批发价");
        //     return false;
        // }


        if (this.props.choosedCategory.catCode == undefined || this.props.choosedCategory.catCode == "") {
            toast("请选择商品类别");
            return false;
        }

        return true;

    };


    /**
     * 编辑基本属性
     * **/
    editProperty = () => {
        this.props.naviPush("Property", {id: 30});
    };


    submitProduct = () => {

        if (!this.checkValue()) {
            return;
        }

        let params = {
            token: this.props.token,
            goodsName: this.state.name,
            catCode: this.props.choosedCategory.catCode == undefined ? "" : this.props.choosedCategory.catCode,
            // marketPrice: this.state.marketPrice * 100,
            shopPrice: this.state.shopPrice * 100,
            // tradePrice: this.state.tradePrice * 100,
            goodsThumb: this.state.img,
            goodsBrief: this.state.remark,
            goodsSlider: this
                .state
                .slides
                .join(";"),
            brand: this.props.choosedBrand
        };
        const self = this;

        if (this.isEdit) {
            params.goodsId = this.goodsId;
            this.props.updateProduct(params, () => {
                toast("保存成功");
                self.props.naviPush("Property", {id: self.goodsId, catCode: self.props.choosedCategory.catCode});
            })
        } else {
            this.props.addProduct(params, (res) => {
                let goods = res.data.goods;
                let goodsId = goods.goodsId;
                self.props.naviPush("Property", {id: goodsId, catCode: self.props.choosedCategory.catCode});
            })
        }
    };

    chooseProductSlide = () => {
        this.imgType = 0;
        this
            .ActionSheet
            .show()
    }

    chooseProductImg = () => {
        this.imgType = 1;
        this
            .ActionSheet
            .show()
    }

    TaghandlePress = (i) => {
        if (i != 0) {
            this.setState({tag: tag_options[i]});
        }
    };


    BackAction = (i) => {
        if (i == 0) {
            this.props.naviBack();
        }
        ;
    };

    handlePress = (i) => {

        let type = "choose";
        let size_w = 0;
        let size_h = 0;
        if (i == 1) {
            type = "takephoto"
        } else if (i == 2) {
            type = "choose"
        } else {
            return;
        }

        if (this.imgType == 0) {
            size_w = 600;
            size_h = 500;
        } else {
            size_w = 500;
            size_h = 600;
        }

        const self = this;
        let oldslides = this.state.slides;
        getQiniuToken((data) => {
            let params = {
                type: type,
                size_w: size_w,
                size_h: size_h,
                token: data.token,
                filetag: "product"
            }
            chooseImage(params, (data) => {
                if (self.imgType == 0) {
                    oldslides.push(config.qiniuUrl + data.imgs);
                    self.setState({slides: oldslides});
                } else if (self.imgType == 1) {
                    self.setState({
                        img: config.qiniuUrl + data.imgs
                    });
                }
            });
        })
    }

    chooseCategory = () => {
        this.props.naviPush("ProductCategory", {catId: this.catId});
    };

    // editDetail = () => {
    //     const self = this;
    //     editRichContent({
    //         title: "编辑",
    //         filetag: "product",
    //         value: this.state.detail
    //     }, (value) => {
    //         self.setState({detail: value.value});
    //     })
    // };


    chooseBrand = () => {
        this.props.naviPush("ProductBrand", {});
    };

    addImage = () => {
        this.imgType = 0;
        this
            .ActionSheet
            .show()
    }

    deleteImage = (i) => {
        let imgs = this.state.slides;
        imgs.splice(i, 1);
        this.setState({slides: imgs});
    };

    render() {

        const images = this.state.slides;

        let productImagesView;
        if (images.length > 0) {
            productImagesView = <CLImagesView
                deleteImage=
                    {(i) => {
                        this.deleteImage(i)
                    }}
                addImage=
                    {() => {
                        this.addImage()
                    }}
                images={images}/>
        } else {
            productImagesView = <TouchableOpacity onPress={() => this.chooseProductSlide()}>
                <Image
                    style={{
                        width: 80,
                        height: 80
                    }}
                    source={require('../../image/takephoto.png')}/>
            </TouchableOpacity>
        }

        // let priceString = "" + this.state.marketPrice;
        let discountPriceString = "" + this.state.shopPrice;
        let tradePriceString = "" + this.state.tradePrice;

        return <LmmKeyboardAvoidingView keyboardVerticalOffset={ 64 }>
            <ScrollView>
                <View>
                    <StepInfo backgroundColor='#f8f7f7' step={1} index={0}/>
                    <View style={styles.productTop}>
                        {productImagesView}
                    </View>
                    <TouchableOpacity onPress={() => this.chooseProductImg()}>
                        <View style={styles.productImg}>
                            <Text
                                style={{
                                    fontSize: 16,
                                    marginLeft: 10
                                }}>商品主图</Text>
                            <Image
                                style={{
                                    width: 50,
                                    height: 60
                                }}
                                source={{
                                    uri: this.state.img
                                }}/>
                        </View>
                    </TouchableOpacity>
                </View>
                <View>
                    <View
                        style={{
                            marginTop: 1,
                            backgroundColor: "white"
                        }}>
                        <CLEditView
                            value={this.state.name}
                            title="商品名称："
                            placeholder="请输入商品名称"
                            onChangeText={(text) => {
                                this.setState({name: text});
                            }}/>
                    </View>
                    {/*<View*/}
                        {/*style={{*/}
                            {/*marginTop: 1,*/}
                            {/*backgroundColor: "white"*/}
                        {/*}}>*/}
                        {/*<CLEditView*/}
                            {/*value={priceString}*/}
                            {/*title="市场价："*/}
                            {/*keyboardType='numeric'*/}
                            {/*placeholder="请输入商品市场（元）"*/}
                            {/*onChangeText={(text) => {*/}
                                {/*this.setState({marketPrice: text});*/}
                            {/*}}/>*/}
                    {/*</View>*/}
                    <View
                        style={{
                            marginTop: 1,
                            backgroundColor: "white"
                        }}>
                        <CLEditView
                            value={discountPriceString}
                            title="零售价格："
                            keyboardType='numeric'
                            placeholder="请输入商品零售价（元）"
                            onChangeText={(text) => {
                                this.setState({shopPrice: text});
                            }}/>
                    </View>

                    {/* <View
                        style={{
                            marginTop: 1,
                            backgroundColor: "white"
                        }}>
                        <CLEditView
                            value={tradePriceString}
                            title="批发价："
                            keyboardType='numeric'
                            placeholder="请输入商品批发价（元）"
                            onChangeText={(text) => {
                                this.setState({tradePrice: text});
                            }}/>
                    </View> */}

                    <View
                        style={{
                            marginTop: 1,
                            backgroundColor: "white"
                        }}>
                        <CLListItem
                            onPress={() => {
                                this.chooseCategory()
                            }}
                            title="商品类别："
                            subTitle={this.props.choosedCategory.catName}/>
                    </View>

                    <View
                        style={{
                            marginTop: 1,
                            backgroundColor: "white"
                        }}>
                        <TextInput
                            value={this.state.remark}
                            placeholder="请输入简述"
                            editable={true}
                            onChangeText={(text) => {
                                this.setState({remark: text});
                            }}
                            underlineColorAndroid={'transparent'}
                            style={{
                                marginLeft: 10,
                                padding: 0,
                                height: 50,
                                flex: 1,
                                borderWidth: 0
                            }}/>
                    </View>
                </View>

                {/*<View*/}
                {/*style={{*/}
                {/*marginTop: 10,*/}
                {/*backgroundColor: "white"*/}
                {/*}}>*/}
                {/*<CLListItem*/}
                {/*onPress={() => {*/}
                {/*this*/}
                {/*.TAGActionSheet*/}
                {/*.show()*/}
                {/*}}*/}
                {/*title="产品说明："*/}
                {/*subTitle={this.state.tag}/>*/}
                {/*</View>*/}
                {/*<View*/}
                    {/*style={{*/}
                        {/*marginTop: 10,*/}
                        {/*backgroundColor: "white"*/}
                    {/*}}>*/}
                    {/*<CLListItem*/}
                        {/*onPress={() => this.chooseBrand()}*/}
                        {/*title="品牌："*/}
                        {/*subTitle={this.props.choosedBrand}/>*/}
                {/*</View>*/}

                <TouchableOpacity
                    onPress={() => {
                        this.submitProduct()
                    }}>
                    <View style={styles.submitButton}>
                        <Text style={{
                            color: "white"
                        }}>下一步</Text>
                    </View>
                </TouchableOpacity>

                <ActionSheet
                    ref={o => this.ActionSheet = o}
                    title="选择图片"
                    options={options}
                    cancelButtonIndex={CANCEL_INDEX}
                    destructiveButtonIndex={DESTRUCTIVE_INDEX}
                    onPress={this.handlePress}/>

                <ActionSheet
                    ref={o => this.TAGActionSheet = o}
                    title="产品说明"
                    options={tag_options}
                    cancelButtonIndex={CANCEL_INDEX}
                    destructiveButtonIndex={TAG_DESTRUCTIVE_INDEX}
                    onPress={this.TaghandlePress}/>

                <ActionSheet
                    ref={o => this.BackActionSheet = o}
                    title="是否退出"
                    cancelButtonIndex={1}
                    destructiveButtonIndex={3}
                    onPress={this.BackAction}
                    options={backoptions}/>

            </ScrollView>
        </LmmKeyboardAvoidingView>
    }

}


const mapStateToProps = (state) => {
    return {
        token: state.mainmodel.token,
        choosedCategory: state.product.chooseCategory,
        choosedBrand: state.product.chooseBrand
    }
};

const mapDispatchToProps = (dispatch) => {
    return {
        addProduct: (params, callback) => {
            dispatch(addProduct(params, callback))
        },
        naviPush: (routeName, params) => {
            dispatch(naviPush(routeName, params))
        },
        naviBack: (routeName) => {
            dispatch(naviBack(routeName))
        },
        updateProduct: (params, callback) => {
            dispatch(updateProduct(params, callback))
        },
        getProductCategoryDetail: (code) => {
            dispatch(getProductCategoryDetail(code));
        },
        chooseCategory: (item) => {
            dispatch(chooseCategory(item));
        },
        chooseBrand: (item) => {
            dispatch(chooseBrand(item));
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps,)(ProductAdd);